﻿#include "ThreadManager.h"
#include "Thread.h"

namespace sky
{
    ThreadManager::ThreadManager(void)
    {

    }

    ThreadManager::~ThreadManager(void)
    {
        m_listThread.clear();
    }

    // 添加线程
    void ThreadManager::addThread(Thread *pThread)
    {
        if (NULL == pThread)
        {
            return;
        }

        removeThread(pThread);

        m_listThread.push_back(pThread);
    }

    // 移除线程
    void ThreadManager::removeThread(Thread *pThread)
    {
        for (THREAD_LIST::iterator itr = m_listThread.begin(); itr != m_listThread.end(); ++itr)
        {
            if ((*itr) == pThread)
            {
                m_listThread.erase(itr);
                return;
            }
        }
    }


    // 通知所有线程停止
    void ThreadManager::stopAll()
    {
        Thread * pThread = NULL;
        for (THREAD_LIST::iterator itr = m_listThread.begin(); itr != m_listThread.end(); ++itr)
        {
            pThread = (*itr);
            if (pThread)
            {
                pThread->notifyStop();
            }
        }
    }

    // 所有线程是否已经停止
    bool ThreadManager::allThreadIsClose()
    {

        Thread * pThread = NULL;
        for (THREAD_LIST::iterator itr = m_listThread.begin(); itr != m_listThread.end(); ++itr)
        {
            pThread = (*itr);
            if (pThread)
            {
                if (false == pThread->isClose())
                {
                    return false;
                }
            }
        }

        return true;
    }

    SKY_API IThreadManager * getThreadManager()
    {
        return &ThreadManager::getInstance();
    }

} // namespace sky
